﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class Administrators : ClassManager.SessionManagerPage
    {
        private void GetAdministratorsByCompanyID()
        {
            SessionManager objSessionManager = new SessionManager();
            objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            AdminGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.AdministratorsProvider.GetByCompanyID(objSessionManager.CompanyIDSelectedComboBox);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.AdministratorsColumn.AdminUsername.ToString();
                expression.SetSortOrder("Ascending");
                this.AdminGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void AdminGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetAdministratorsByCompanyID();

            AdminGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
        }
        

        protected void AdminGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                
                GPSTrackingDBV2.Entities.Administrators AdminEntity = ClassManager.InvokeEntityManager.Invoke_Administrator_Entity(e);
                AdminEntity.Password = EncryptaionManager.EncryptionManager.Encrypt(AdminEntity.Password, new System.Security.Cryptography.SHA256CryptoServiceProvider());
                AdminEntity.CreationDate = DateTime.Now;
                AdminEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;

                GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.Insert(AdminEntity);
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede registrar la información.");
            }
        }

        protected void AdminGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                GridEditableItem item = e.Item as GridEditableItem;
   
                GPSTrackingDBV2.Entities.Administrators AdminEntity = ClassManager.InvokeEntityManager.Invoke_Administrator_Entity(e);
                
                AdminEntity.OriginalAdminUsername = AdminEntity.AdminUsername;
                AdminEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;
                AdminEntity.OriginalCompanyId = AdminEntity.CompanyId;
                AdminEntity.Password = item.SavedOldValues["Password"].ToString();

                GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.Update(AdminEntity);
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede actualizar la información.");
            }
        }

        protected void AdminGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                GPSTrackingDBV2.Entities.Administrators AdminEntity = ClassManager.InvokeEntityManager.Invoke_Administrator_Entity(e);

                AdminEntity.AdminUsername = AdminEntity.AdminUsername;

                GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.Delete(AdminEntity.AdminUsername, objSessionManager.CompanyIDSelectedComboBox);
         
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede eliminar el registro porque el administrador se encuentra asociados a otros registros.");
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Administradores...');", true);
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            AdminGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in AdminGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
                else
                {
                    if (column is GridCheckBoxColumn)
                    {
                        GridCheckBoxColumn boundCheckColumn = column as GridCheckBoxColumn;
                        boundCheckColumn.CurrentFilterValue = "true";
                    }
                }
            }


            AdminGrid.MasterTableView.Rebind();
        }

        protected void AdminGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.OwnerTableView.IsItemInserted && e.Item.IsInEditMode) //item is about to be inserted  
            {
                TextBox txtid;
                GridEditableItem insertItem = (GridEditableItem)e.Item;
                txtid = (TextBox)insertItem["Password"].Controls[0];
                txtid.ReadOnly = false;
                txtid.TextMode = TextBoxMode.Password;
                txtid = (TextBox)insertItem["AdminUsername"].Controls[0];
                txtid.ReadOnly = false;
            }
            if (!(e.Item.OwnerTableView.IsItemInserted) && e.Item.IsInEditMode)   //item is about to be edit
            {
                TextBox txtid;
                GridEditableItem editItem = (GridEditableItem)e.Item;
                txtid = (TextBox)editItem["Password"].Controls[0];
                txtid.ReadOnly = true;
                txtid.TextMode = TextBoxMode.Password;
                txtid = (TextBox)editItem["AdminUsername"].Controls[0];
                txtid.ReadOnly = true;
            }
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }
    }
}